package icu.guodapeng.gateway.filter

import com.nimbusds.jose.JWSObject
import org.springframework.cloud.gateway.filter.GatewayFilterChain
import org.springframework.cloud.gateway.filter.GlobalFilter
import org.springframework.core.Ordered
import org.springframework.stereotype.Component
import org.springframework.web.server.ServerWebExchange
import reactor.core.publisher.Mono
import org.slf4j.Logger
import org.slf4j.LoggerFactory
import org.springframework.http.server.reactive.ServerHttpRequest


/**
 * 将登录用户的 JWT 转化成用户信息的全局过滤器
 */
@Component
class AuthGlobalFilter : GlobalFilter, Ordered {

    private val logger: Logger = LoggerFactory.getLogger(this::class.java)

    override fun filter(exchange: ServerWebExchange, chain: GatewayFilterChain): Mono<Void> {
        val token: String? = exchange.request.headers.getFirst("Authorization")
        if (token == null || token.isEmpty() || !token.startsWith("Bearer ")) {
            return chain.filter(exchange)
        }
        //从token中解析用户信息并设置到Header中去
        val realToken = token.replace("Bearer ", "")
        val jwsObject = JWSObject.parse(realToken)
        val userStr = jwsObject.payload.toString()
        logger.info("AuthGlobalFilter.filter() user:{}", userStr)
        val request: ServerHttpRequest = exchange.request.mutate().header("user", userStr).build()

        return chain.filter(exchange.mutate().request(request).build())
    }

    override fun getOrder(): Int = 0
}
